package com.aitesting.controller;


import com.aitesting.common.CommonResult;
import com.aitesting.model.Env;
import com.aitesting.service.EnvService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 测试环境管理
 * @author zz
 * @since 2022-02-20
 */
@Slf4j
@RestController
@RequestMapping("/env")
public class EnvController {
    @Autowired
    private EnvService envService;

    /**
     * 根据id查询环境信息
     * @param id 环境id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public CommonResult<Env> getById(@PathVariable("id") Integer id) {
        return CommonResult.success(envService.getById(id));
    }

    /**
     * 查询所有环境
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public CommonResult<Env> getList() {
        return CommonResult.success(envService.list());
    }

    /**
     * 新增环境
     * @param env 环境对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResult<Env> create(@RequestBody Env env){
        boolean isOk = envService.save(env);
        if (isOk) {
            log.debug("创建环境成功 {}", env);
            return CommonResult.success(env);
        }else {
            log.error("新增环境失败,数据不合法 {}", env);
            return CommonResult.failed();
        }
    }

    /**
     * 根据id删除环境
     * @param id 环境id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public CommonResult<Env> delete(@PathVariable Integer id) {
        boolean isOk = envService.removeById(id);
        if (isOk) {
            return CommonResult.success(null);
        }else {
            return CommonResult.failed();
        }
    }

    /**
     * 根据id更新环境
     * @param env 环境对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public CommonResult<Env> update(@RequestBody Env env) {
        boolean isOk = envService.updateById(env);
        if (isOk) {
            log.debug("更新环境成功 {}", env);
            return CommonResult.success(env);
        }else {
            log.error("更新环境失败,数据不合法 {}", env);
            return CommonResult.failed();
        }
    }
}

